package com.joinway.framework.text.java;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;

import com.joinway.framework.extension.groovy.DomainUtils;
import com.joinway.framework.text.sql.bean.Column;

public final class JavaBuilder {

	private final static Map<String, String> typeMap = new HashMap<>();
	
	static{
		typeMap.put("varchar", "String");
		typeMap.put("time", "Date");
		typeMap.put("timestamp", "Date");
		typeMap.put("datetime", "Date");
		typeMap.put("date", "Date");
		typeMap.put("year", "Date");
		typeMap.put("tinyint", "int");
		typeMap.put("tinyint(1)", "boolean");
		typeMap.put("smallint", "int");
		typeMap.put("mediumint", "int");
		typeMap.put("int", "long");
		typeMap.put("bigint", "long");
		typeMap.put("decimal", "double");
		typeMap.put("int unsigned", "long");
		typeMap.put("bigint unsigned", "long");
		typeMap.put("char", "String");
		typeMap.put("blob", "byte[]");
		typeMap.put("tinyblob", "byte[]");
		typeMap.put("mediumblob", "byte[]");
		typeMap.put("longblob", "byte[]");
		typeMap.put("text", "String");
		typeMap.put("tinytext", "String");
		typeMap.put("mediumtext", "String");
		typeMap.put("longtext", "String");
		typeMap.put("int unsigned", "long");
		typeMap.put("bit(1)", "boolean");
		typeMap.put("bit", "byte[]");
		typeMap.put("binary", "byte[]");
		typeMap.put("varbinary", "byte[]");
	}

	public static List<JavaField> buildJavaFields(List<Column> columns){
		List<JavaField> fields = new LinkedList<>();
		
		if(CollectionUtils.isNotEmpty(columns)){
			for(Column column : columns){
				JavaField field = new JavaField();
				
//				String dbType = column.getType();
//				String len = column.getLength();
//				String tyepWithLen = dbType + "(" + len + ")";
				
				String type = buildJavaType(column);
				field.setType(type);
//				boolean foundMatch = StringUtils.isNotBlank(type);
//				if(typeMap.containsKey(tyepWithLen.toLowerCase())){
//					field.setType(typeMap.get(tyepWithLen.toLowerCase()));
//					foundMatch = true;
//				}else if(typeMap.containsKey(dbType.toLowerCase())){
//					field.setType(typeMap.get(dbType.toLowerCase()));
//					foundMatch = true;
//				}
				
//				if(StringUtils.isNotBlank(type)){
				field.setName(DomainUtils.convertToDomainFieldName(column.getName()));
				fields.add(field);
//				}
			}
		}
		
		return fields;
	}
	
	public static String buildJavaType(Column column){
		String type = null;
		
		String dbType = column.getType();
		String len = column.getLength();
		String tyepWithLen = dbType + "(" + len + ")";

		if(typeMap.containsKey(tyepWithLen.toLowerCase())){
			type = typeMap.get(tyepWithLen.toLowerCase());
		}else if(typeMap.containsKey(dbType.toLowerCase())){
			type = typeMap.get(dbType.toLowerCase());
		}
		
		return type;
	}
	
	private JavaBuilder(){}
}
